<template>
    <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false" width="50%" top="60px">
        <!-- <el-tabs v-model="activeName">
            <el-tab-pane label="基本信息" name="first"></el-tab-pane>
            <el-tab-pane label="商品特色" name="second"></el-tab-pane>
            <el-tab-pane label="购买须知" name="third"></el-tab-pane>
        </el-tabs> -->
        <el-form style="height:500px;overflow:auto;padding-right:20px" :model="dataForm" :rules="dataRule" ref="dataForm" :label-width="$i18n.locale === 'en-US' ? '170px' : '150px'">
            <el-row v-if="activeName=='first'">
                <el-col :span="12">
                    <el-form-item label="商品名称" prop="name">
                        <el-input v-model="dataForm.name"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="价格" prop="price">
                        <el-input v-model="dataForm.price" type="number"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="折扣价" prop="discountPrice">
                        <el-input v-model="dataForm.discountPrice" type="number"></el-input>
                    </el-form-item>
                </el-col>
                <!-- <el-col :span="12">
                    <el-form-item label="所属渔家乐" prop="fishermanId">
                        <el-select v-model="dataForm.fishermanId" placeholder="所属渔家乐" clearable style="width:100%">
                            <el-option v-for="item in fishOptions" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col> -->
                <!-- <el-col :span="12">
                    <el-form-item label="标签" prop="type">
                        <ren-select v-model="dataForm.typeArr" multiple dict-type="FishermanType" placeholder="请选择标签" style="width:100%"></ren-select>
                    </el-form-item>
                </el-col> -->
                <el-col :span="12">
          <el-form-item label="上下架" prop="status">
            <el-select
              v-model="dataForm.status"
              clearable
              style="width: 100%"
            >
              <el-option label="上架" :value="0"> </el-option>
              <el-option label="下架" :value="1"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
                    <el-form-item label="开始日期" prop="activityStartTime">
                        <el-date-picker style="width:100%" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" v-model="dataForm.activityStartTime" placeholder="开始日期">
                    </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="结束日期" prop="activityEndTime">
                        <el-date-picker style="width:100%" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" v-model="dataForm.activityEndTime" placeholder="结束日期">
                    </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
          <el-form-item label="限制" prop="limitFlag">
            <el-select
              v-model="dataForm.limitFlag"
              clearable
              style="width: 100%"
            >
              <el-option label="不限制" :value="1"> </el-option>
              <el-option label="限制" :value="2"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
          </el-form-item>
                <el-col :span="12">
                    <el-form-item label="退款说明" prop="refundRemark">
                        <el-input v-model="dataForm.refundRemark"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24" v-for="(item,i) in noticeList" :key="i">
                    <el-form-item :label="`${'须知' + (i + 1) }`">
                        <el-input v-model="item.notice" ></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24" style="padding-left:150px;margin-bottom:20px ;">
                    <el-button type="danger" size="mini"  @click="deleteNotice(i)" v-if="index=this.noticeList.length-1">删除须知</el-button>
                        <el-button type="primary" size="mini"  @click="addNotice()">添加须知</el-button>
                </el-col>
                <el-col :span="24" v-for="(item,i) in useRuleList" :key="i">
                    <el-form-item :label="`${'使用规则' + (i + 1) }`" >
                        <el-input v-model="item.useRule"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24" style="padding-left:150px;margin-bottom:20px ;">
                    <el-button type="danger" size="mini"  @click="deleteUseRule(i)" v-if="index=this.useRuleList.length-1">删除使用规则</el-button>
                        <el-button type="primary" size="mini"  @click="addUseRule()">添加使用规则</el-button>
                </el-col>
                <el-col :span="24" class="detail" v-for="(item,i) in detail" :key="i">
                    <el-form-item label="商品明细-名称" prop="">
                        <el-input v-model="item.name" style="width:150px"></el-input>
                    </el-form-item>
                    <el-form-item label="商品明细-数量" prop="">
                        <el-input v-model="item.number" style="width:150px"></el-input>
                    </el-form-item>
                    <el-form-item label="商品明细-价格" prop="">
                        <el-input v-model="item.price" style="width:150px"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24" style="padding-left:150px;margin-bottom:20px ;">
                    <el-button type="danger"  size="mini" @click="deleteDays(i)" v-if="index=this.detail.length-1">删除明细</el-button>
                        <el-button type="primary" size="mini" @click="addDays()">添加明细</el-button>
                </el-col>
                <!-- <el-col :span="12">
                    <el-form-item label="适用人数" prop="suitNum">
                        <el-input v-model="dataForm.suitNum"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="所需人数" prop="needNum">
                        <el-input v-model="dataForm.needNum"></el-input>
                    </el-form-item>
                </el-col> -->
                <el-col :span="24">
          <p class="pdl60">
            商品封面<span>(支持png、jpg，建议尺寸750*980px，最多6张)</span>
          </p>
        </el-col>
                <!-- <el-col :span="12">
          <el-form-item label="" prop="coverImg">
            <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :on-success="
                (res, file, fileList) => successHandle(res, file, fileList)
              "
              :before-upload="beforeUploadHandle"
            >
              <img
                v-if="dataForm.coverImg"
                :src="dataForm.coverImg"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
                    <el-form-item label="" >
                        <el-upload :action="url" :file-list="fileList" :limit="6" :before-upload="beforeUploadHandle" list-type="picture-card" :on-success="successHandle" :on-remove="handleRemove">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            <template v-if="activeName=='second'">
                <editor-vue :content="dataForm.feature" @EditorChange="getEditor" ref="infoIntroduceRef"></editor-vue>
            </template>
            <!-- <template v-if="activeName=='third'">
                <quill-editor class="ql-container" ref="myQuillEditor" v-model="dataForm.notice" />
            </template> -->
        </el-form>
        <template slot="footer">
            <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
            <el-button type="primary" @click="dataFormSubmitHandle()">{{
            $t("confirm")
          }}</el-button>
        </template>
    </el-dialog>
    </template>
    
    <script>
    import Cookies from "js-cookie";
    import debounce from "lodash/debounce";
    import editorVue from '@/components/editor'
import { join } from "lodash";
    export default {
        data() {
            return {
                fileList: [],
                url: `${
            window.SITE_CONFIG["apiURL"]
          }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
                dialogImageUrl: '',
                dialogVisible: false,
                visible: false,
                activeName: "first",
                fishOptions: [],
                //商品明细数组
                detail:[{
                    name:'',
                    number:'',
                    price:'',
                }],
                //商品须知数组
                noticeList:[
                {
                    notice:''
                }
                ],
                //商品规则数组
                useRuleList:[
                {
                    useRule:''
                }
                ],
                dataForm: {
                    merchantId:'',
                    id: "",
                    name:'',
                    price:"",
                    status:0,
                    limitFlag:1,
                    discountPrice:'',
                    refundRemark:'',
                    activityStartTime:'',
                    activityEndTime:'',
                    notice:'',
                    useRule:"",
                    coverImg:[],
                    productsDetail:'',
                },
            };
        },
        computed: {
            dataRule() {
                return {
                    name: [{
                        required: true,
                        message: this.$t("validate.required"),
                        trigger: "blur",
                    }, ],
                    price: [{
                        required: true,
                        message: this.$t("validate.required"),
                        trigger: "blur",
                    }, ],        
                    discountPrice: [{
                        required: true,
                        message: this.$t("validate.required"),
                        trigger: "blur",
                    }, ],
                    notice: [{
                        required: true,
                        message: this.$t("validate.required"),
                        trigger: "blur",
                    }, ],
                    fishermanId: [{
                        required: true,
                        message: this.$t("validate.required"),
                        trigger: "blur",
                    }, ],
                };
            },
        },
        components: {
            editorVue
        },
        watch: {
             "activeName"(newval, oldval) {
                if (newval == 'second') {
                    this.$nextTick(() => {
                        this.$refs.infoIntroduceRef.init();
                    })
                }
            },
        },
        created() {
        },
        methods: {
              getEditor(val) {
                this.dataForm.information = val;
            },
            //添加明细
            addDays() {
            this.detail.push(
                {
                    name:'',
                    number:'',
                    price:'',
                }
            )
        },   
        //删除明细
            deleteDays(index) {
            this.detail.splice(index, 1)
        },
                    //添加须知
            addNotice(){
                this.noticeList.push(
                {
                    notice:'',
                }
            )
            },
            //删除须知
            deleteNotice(index){
                this.noticeList.splice(index, 1)
            },
            //添加使用规则
            addUseRule(){
                this.useRuleList.push(
                {
                    useRule:'',
                }
            )
            },
            //删除使用规则
            deleteUseRule(index){
                this.useRuleList.splice(index, 1)
            },
 
            handleRemove(file, fileList) {
            this.fileList = fileList.map((item) => {
                return item.url;
            });
        },
            // 上传之前
    beforeUploadHandle(file) {
      if (
        file.type !== "image/jpg" &&
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$message.error(
          this.$t("upload.tip", {
            format: "jpg、png、gif",
          })
        );
        return false;
      }
    },
            // 上传成功
    successHandle(res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      this.fileList.unshift({
                name: "",
                url: res.data.url,
            });
    },
            init() {
                this.visible = true;
                this.getFishName();
                this.fileList=[],
                this.detail=[{
                    name:'',
                    number:'',
                    price:'',
                }],
                this.noticeList=[{
                    notice:''
                }];
                this.$nextTick(() => {
                     this.activeName="first";
                    this.$refs["dataForm"].resetFields();
                    if (this.dataForm.id) {
                        this.getInfo();
                    }
                });
            },
            getFishName() {
                this.$http.get('/scenic/fisherman/page', {
                    params: {
                        page: 1,
                        limit: -1,
                        merchantType: 10
                    }
                }).then(res => {
                    if (res.data.code == 0) {
                        this.fishOptions = res.data.data.list;
                    }
                })
    
            },
            // 获取信息
            getInfo() {
                this.$http
                    .get("/scenic/merchant/product/" + this.dataForm.id)
                    .then(({
                        data: res
                    }) => {
                        if (res.code !== 0) {
                            return this.$message.error(res.msg);
                        }
                        this.dataForm = {
                            ...this.dataForm,
                            ...res.data,
                        };
                       // let productsDetail = JSON.parse(this.dataForm.productsDetail)
                        console.log(this.dataForm.coverImg.split,'商品明细')
                        let picArr = this.dataForm.coverImg.split(',');
                    for (let i = 0; i < picArr.length; i++) {
                        this.fileList.push({
                            url: picArr[i]
                        })
                    }
                        this.detail = JSON.parse(this.dataForm.productsDetail)
                        this.useRuleList = JSON.parse(this.dataForm.useRule)
                       this.noticeList = JSON.parse(this.dataForm.notice)
                        this.dataForm.typeArr = this.dataForm.type.split(',')
                 
    
                    })
                    .catch(() => {});
            },
            // 表单提交
            dataFormSubmitHandle: debounce(
      function () {
       this.dataForm.productsDetail= JSON.stringify(this.detail)
       this.dataForm.useRule=JSON.stringify(this.useRuleList)
        this.dataForm.notice=JSON.stringify(this.noticeList)
        this.dataForm.merchantId =this.$store.state.user.MerchantId
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          let picArr = [];
                    this.fileList.filter((item => {
                        picArr.push(item.url)
                    }))
                    this.dataForm.coverImg = picArr.join(',');
          this.$http[!this.dataForm.id ? "post" : "put"](
            "/scenic/merchant/product",
            this.dataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      {
        leading: true,
        trailing: false,
      }
    ),
    
        },
    };
    </script>
    
    <style lang="scss" scoped>
        .detail{
            display: flex;
        }
    h3 {
        padding: 30px 0 15px;
        width: 94%;
        margin: 0 auto 30px;
        border-bottom: 1px solid #ddd;
        color: #303133;
        font-size: 22px;
        overflow: hidden;
    }
    
    .aui-content .ql-container {
        height: auto
    }
    
    .ql-container.ql-snow {
        height: 500px;
    }
    
    .rooms .item {
        display: inline-block;
        margin-right: 15px;
        position: relative;
    
        .el-icon-error {
            position: absolute;
            right: 6px;
            top: -6px;
            font-size: 20px;
            color: #dd0606;
        }
    }
    </style>
    